<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="90px">
      <el-row>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户姓名" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="客户手机号" prop="mobile">
          <el-input v-model="queryParams.mobile" placeholder="请输入客户手机号" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <!-- <el-form-item label="日期" prop="applyAuthTimeArray">
          <el-date-picker v-model="queryParams.applyAuthTimeArray" type="daterange" align="right" style="width: 232px"
            value-format="yyyy-MM-dd" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="服务状态" prop="serviceStatus">
          <el-select v-model="queryParams.serviceStatus" placeholder="请选择服务状态" clearable size="small"
            @keyup.enter.native="handleQuery">
            <el-option v-for="dict in serviceStatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="门店" prop="storeId">
          <el-select v-model="queryParams.storeId" placeholder="请选择门店" clearable size="small"
            @keyup.enter.native="handleQuery">
            <el-option v-for="dict in storeInFoOptions" :key="dict.storeId" :label="dict.storeName"
              :value="dict.storeUid" />
          </el-select>
        </el-form-item>

        <el-form-item label="渠道来源" prop="sourcePlatform">
          <el-select v-model="queryParams.sourcePlatform" placeholder="请选择渠道来源" clearable size="small"
            @keyup.enter.native="handleQuery">
            <el-option v-for="dict in sourcePlatformOptions" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="预约类型" prop="subscribeType">
          <el-select v-model="queryParams.subscribeType" placeholder="请选择预约类型" clearable size="small"
            style="width: 232px" @keyup.enter.native="handleQuery">
            <el-option v-for="dict in subscribeTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 22px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
<!--
      <el-row>



      </el-row> -->
    </el-form>

    <el-row class="row-mbinfo">

      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSave">新增</el-button>
      </el-col>

      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col> -->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">

        <el-table-column label="客户名称" align="center" prop="customerName" min-width="100px" />

        
        <el-table-column label="美容师" align="center" prop="nickName" min-width="80px">
          <template slot-scope="scope">
            <el-select @change="changeUserList(scope.row)" v-if="scope.row.sysUserList!=null && scope.row.sysUserList.length>0" v-model="scope.row.technicianId" placeholder="请选择">
              <el-option v-for="item in scope.row.sysUserList" :key="item.userId" :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
            <span v-else>{{ scope.row.nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预约门店" align="center" prop="storeName" min-width="160px" />
        <el-table-column label="服务类型" align="center" prop="serviceTypeStr" />
        <el-table-column label="预约日期" align="center" prop="subscribeDate" />
        <el-table-column label="项目名称" align="center" prop="serviceName" min-width="160px" />
        <el-table-column label="数量" align="center" prop="serviceTimes"  width="60px"/>

        <!-- <el-table-column label="开始时间" align="center" prop="startDate" min-width="130px">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d} {h}:{mi}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endDate" min-width="130px">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d} {h}:{mi}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="性别" align="center" prop="sexStr" width="60px"/>
        <el-table-column label="联系电话" align="center" prop="mobile" min-width="100px" />
        <el-table-column label="渠道来源" align="center" prop="sourcePlatformStr" />
        <el-table-column label="预约类型" align="center" prop="subscribeTypeStr" />





        <el-table-column label="服务状态" align="center" prop="serviceStatusStr" />

        <el-table-column label="操作" align="center" prop="createTime" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-zoom-in" @click="handlee(scope.row)">详情</el-button>
          </template>
        </el-table-column>

        <!-- <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-if="scope.row.dataStatus == '0'" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

  </div>
</template>

<script>

import {
  selectGroup
} from "@/api/platform/store"
import {
  listRecord,editTechnician
} from "@/api/customerService/record";
import imageArraySize from "@/components/ImageUpload/imageArraySize";
import commoditytab from "@/components/Activity/commodityTab";
import SelectedPro from "@/components/radio/SelectedPro";
import selectedA from "@/components/radio/SelectedItem";
import commodityItem from "@/components/radio/commodityItem";

import selectedCoupon from "@/components/radio/SelectedCoupon";
import commodityCoupon from "@/components/radio/commodityCoupon";
import SelectedCard from "@/components/radio/SelectedCard";
import commodityCard from "@/components/radio/commodityCard";
import commodityPro from "@/components/radio/commodityPro";
import { onInput } from "@/utils/util";
export default {
  name: "Brand",
  components: {
    imageArraySize,
    commoditytab,
    SelectedPro,
    selectedA,
    commodityItem,
    selectedCoupon,
    commodityCoupon,
    commodityCard,
    SelectedCard,
    commodityPro,
  },
  data() {
    return {
      sourcePlatformOptions: [
        {
          "value": "applets",
          "label": "小程序"
        },
        {
          "value": "meituan",
          "label": "美团"
        }, {
          "value": "dithering",
          "label": "抖音"
        }
      ],
      subscribeTypeOptions: [
        {
          "value": "customerAppointment",
          "label": "客户预约"
        },
        {
          "value": "thirdParty",
          "label": "第三方"
        }, {
          "value": "supplement",
          "label": "到店补单"
        }
      ], serviceStatusOptions: [
        {
          "value": "0",
          "label": "待服务"
        },
        {
          "value": "1",
          "label": "开始服务"
        }, {
          "value": "2",
          "label": "结束服务"
        }, {
          "value": "3",
          "label": "服务记录"
        }, {
          "value": "4",
          "label": "接受服务"
        }, {
          "value": "99",
          "label": "爽约"
        }, {
          "value": "100",
          "label": "门店关单"
        }],
      // ],   sourcePlatformOptions:[
      //     {
      //       "value":"applets",
      //       "label":"小程序"
      //     },
      //     {
      //       "value":"meituan",
      //       "label":"美团"
      //     },{
      //       "value":"dithering",
      //       "label":"抖音"
      //     }
      // ],


      selectedDataCopy: [{}],
      selectedData: [],
      storeOpen: false,
      selectedDataStore: {},
      couponOpen: false,
      selectedDataCoupon: {},
      cardAOpen: false,
      selectedDataCard: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 储值/系列表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openA: false,
      // 用于类别关联的分类显示
      dialogVisible: false,
      //常用状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        mobile: null,
        storeId: null,
        startTime: null,
        endTime: null,
        applyAuthTimeArray: [],
        sourcePlatform:'',
        subscribeType:'',
      },
      // 商品
      productOpen: false,
      selectedDataProduct: {},

      optionsA: [
        {
          value: "1",
          label: "一月",
        },
        {
          value: "2",
          label: "二月",
        },
        {
          value: "3",
          label: "三月",
        },
        {
          value: "4",
          label: "四月",
        },
        {
          value: "5",
          label: "五月",
        },
        {
          value: "6",
          label: "六月",
        },
        {
          value: "7",
          label: "七月",
        },
        {
          value: "8",
          label: "八月",
        },
        {
          value: "9",
          label: "九月",
        },
        {
          value: "10",
          label: "十月",
        },
        {
          value: "11",
          label: "十一月",
        },
        {
          value: "12",
          label: "十二月",
        },
      ],

      options: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "0",
          label: "否",
        },
      ],
      oldList:[],
      // 表单参数
      form: {
        rechargeName: "",
        dialogImageUrl: "",
        dataPriority: "",
        isDataValue: "",
        rightType: "",
      },
      storeInFoOptions: [],
      // 表单校验
      rules: {
        rechargeName: [
          {
            required: true,
            message: "储值名称不能为空",
            trigger: "blur",
          },
        ],
        isDataValue: [
          {
            required: true,
            message: "储值属性不能为空",
            trigger: "change",
          },
        ],
        rightType: [
          {
            required: true,
            message: "储值权益不能为空",
            trigger: "change",
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_data_status").then((response) => {
      this.statusOptions = response.data;
    });
    selectGroup().then(response => {
      this.storeInFoOptions = response.data || [];
    });
  },
  watch: {
    selectedDataCopy: {
      deep: true,
      handler(newVal, oldVal) {
        let obj = newVal[0];
        if (Object.keys(obj).length > 0) {
          let arr = Object.keys(obj),
            isValue = false;
          arr.forEach((item) => {
            if (obj[item]) {
              isValue = true;
            }
          });
          if (isValue) {
            this.form.isDataValue = "1";
          } else {
            this.form.isDataValue = "";
          }
        } else {
          this.form.isDataValue = "";
        }
      },
    },
  },
  methods: {
    onInput,
    handlee(row) {
      this.$router.push("/subscribeService/record/data/" + row.subscribeId);
    },
    tabResponCard() {
      this.selectedDataCard = {};
    },
    tabResponCoupon() {
      this.selectedDataCoupon = {};
    },
    tabRespon() {
      this.selectedDataStore = {};
    },
    tabResponProduct() {
      this.selectedDataProduct = {};
    },
    dataPriorityInput(value) {
      let js = value + "";
      return js.replace(/^(0+)|[^\d]+/g, "");
    },
    /** 查询储值/系列列表 */
    getList() {
      if (this.queryParams.applyAuthTimeArray != null && this.queryParams.applyAuthTimeArray.length > 0) {
        let arr = this.queryParams.applyAuthTimeArray;
        this.queryParams.startTime = arr[0] + " 00:00:00";
        this.queryParams.endTime = arr[1] + " 23:59:59";
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      this.loading = true;
      listRecord(this.queryParams).then((response) => {
        this.brandList = response.rows;
        this.oldList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    p(s) {
      return s < 10 ? "0" + s : s;
    },

    selectCommodityCoupon() {
      this.$forceUpdate();
      this.couponOpen = true;
      console.log(this.couponOpen);
      // this.$nextTick(() => {
      //   this.$refs["selTableCoupon"].greet(this.selectedDataCoupon);
      // });
    },

    //调用子组件中方法，向子组件传值
    selectCommodity() {
      this.$forceUpdate();
      this.openA = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedData);
      });
    },

    selectCommodityCard() {
      this.$forceUpdate();
      this.cardAOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableCard"].greet(this.selectedDataCard);
      });
    },

    selectCommodityProduct() {
      this.productOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableProduct"].greet(this.selectedDataProduct);
      });
    },

    multipleSelection(data) {
      this.openA = false;
      this.selectedData = data;
      // this.$nextTick(() => {
      //   this.$refs.child.getList();
      // });
    },

    selectCommodityService() {
      this.$forceUpdate();
      this.storeOpen = true;
      // this.$nextTick(() => {
      //   this.$refs["selTable"].greet(this.selectedDataStore);
      // });
    },

    toCloseBoxCoupon() {
      this.couponOpen = false;
    },

    toCloseBoxCard() {
      this.cardAOpen = false;
    },

    toCloseBoxProduct() {
      this.productOpen = false;
    },

    toCloseBoxStore() {
      this.storeOpen = false;
    },

    toCloseBox() {
      this.open = false;
    },

    multipleSelectionCoupon(data) {
      this.couponOpen = false;
      this.selectedDataCoupon = data;
      this.$nextTick(() => {
        this.$refs.childCoupon.getList();
      });
    },

    multipleSelectionStore(data) {
      this.storeOpen = false;
      this.selectedDataStore = data;
      this.$nextTick(() => {
        this.$refs.childStore.getList();
      });
    },

    multipleSelectionCard(data) {
      this.cardAOpen = false;
      this.selectedDataCard = data;
      this.$nextTick(() => {
        this.$refs.childCard.getList();
      });
    },

    multipleSelectionProduct(data) {
      this.productOpen = false;
      this.selectedDataProduct = data;
      this.$nextTick(() => {
        this.$refs.childProduct.getList();
      });
    },

    getSTime(val) {
      //手动赋值，使其通过校验

      const d = new Date(val[0]);
      const resDate =
        d.getFullYear() +
        "-" +
        this.p(d.getMonth() + 1) +
        "-" +
        this.p(d.getDate());
      const resTime =
        this.p(d.getHours()) +
        ":" +
        this.p(d.getMinutes()) +
        ":" +
        this.p(d.getSeconds());
      this.form.startTime = resDate + " " + resTime;
      const c = new Date(val[1]);
      const resDatec =
        c.getFullYear() +
        "-" +
        this.p(c.getMonth() + 1) +
        "-" +
        this.p(c.getDate());
      const resTimec =
        this.p(c.getHours()) +
        ":" +
        this.p(c.getMinutes()) +
        ":" +
        this.p(c.getSeconds());
      this.form.endTime = resDatec + " " + resTimec;
    },

    handleChange(value) {
      console.log(value);
    },

    handleRemove(file, fileList) { },
    handlePictureCardPreviewLogo(file) {
      this.logoUr = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewImg(file) {
      this.deviceImage = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 关联的取消按钮
    cancelBrand() {
      this.openBrand = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // this.form = {
      //   rechargeName: null,
      //   rechargeIcon: null,
      //   isDataValue: '',
      //   dataPriority: 10,
      //   rightType: ''
      // };
      this.form.rechargeName = null;
      this.form.rechargeIcon = null;
      this.form.isDataValue = "";
      this.form.dataPriority = 10;
      this.form.rightType = "";
      this.resetForm("form");
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 储值菜单 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.rechargeId);
      this.names = selection.map((item) => item.rechargeName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm(
        '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateBrandStatus(row.rechargeId, row.dataStatus);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
    },

    // 状态修改
    handleStatusChangeA(row) {
      let text = row.isRecommend === "0" ? "不推荐" : "推荐";
      this.$confirm(
        '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateBrandStatusA(row.rechargeId, row.isRecommend);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.isRecommend = row.isRecommend === "0" ? "1" : "0";
        });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.selectedDataCopy = [{}];
      this.reset();
      this.open = true;
      this.title = "添加储值";
    },
    handleSave() {
      this.$router.push("/service/recharge/data/");

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push("/service/recharge/editData/" + row.rechargeId);

      // this.reset();
      // const rechargeId = row.rechargeId || this.ids;
      // getBrand(rechargeId).then((response) => {
      //   this.form = response.data;
      //   console.log(this.form);
      //   this.selectedDataCopy[0].rechargeMoney = this.form.rechargeMoney;
      //   this.selectedDataCopy[0].goldCoin = this.form.goldCoin;
      //   this.selectedDataCopy[0].silverCoin = this.form.silverCoin;
      //   this.selectedDataCopy[0].score = this.form.score;
      //   this.form.timeValue = [];
      //   this.form.timeValue.push(this.form.startTime || "");
      //   this.form.timeValue.push(this.form.endTime || "");
      //   this.open = true;
      //   this.title = "修改储值";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.childs.selectImgs();
      this.form.rechargeMoney = this.selectedDataCopy[0].rechargeMoney;
      this.form.goldCoin = this.selectedDataCopy[0].goldCoin;
      this.form.silverCoin = this.selectedDataCopy[0].silverCoin;
      this.form.score = this.selectedDataCopy[0].score;

      // 选择权益
      if (this.form.rightType == "coupon") {
        // 获取id this.selectedDataCoupon
        this.form.rightObjectId = this.selectedDataCoupon.couponUid;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择优惠券数据");
          return;
        }
      } else if (this.form.rightType == "card") {
        // 获取id  this.selectedDataCard
        this.form.rightObjectId = this.selectedDataCard.cardId;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择套餐卡数据");
          return;
        }
      } else if (this.form.rightType == "service") {
        // 获取id  this.selectedDataStore
        this.form.rightObjectId = this.selectedDataStore.itemId;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择服务项目数据");
          return;
        }
      } else if (this.form.rightType == "product") {
        // 获取id  this.selectedDataProduct
        this.form.rightObjectId = this.selectedDataProduct.productUid;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择商品数据");
          return;
        }
      }

      console.log(this.form);
      return
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.rechargeId != null) {
            updateBrand(this.form).then((response) => {
              // updateRight(this.form)
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {};
              this.selectedDataCoupon = {};
              this.selectedDataStore = {};
              this.selectedDataProduct = {};
            });
          } else {
            addBrand(this.form).then((response) => {
              // form.rightObjectId=
              // addRight(this.form)
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {};
              this.selectedDataCoupon = {};
              this.selectedDataStore = {};
              this.selectedDataProduct = {};
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.rechargeId || this.ids;
      const names = row.rechargeName || this.names;
      this.$confirm('是否确认删除储值名称为"' + names + '"的储值?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delBrand(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/brand/export",
        {
          ...this.queryParams,
        },
        `商品储值.xlsx`
      );
    },
    changeUserList(row){
      const _this = this;
        let data = {
          subscribeId:row.subscribeId,
          technicianId:row.technicianId
        }

        editTechnician(data).then(response=>{
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function(){
          let id = 0;
          _this.oldList.forEach(vo=>{
            if(row.subscribeId = vo.subscribeId){
              id = vo.technicianId;
            }
          })
          row.technicianId = id;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.treeOne {
  display: inline-block;
  margin-right: 200px;
}

.treeTwo {
  display: inline-block;
}

.image-rows {
  width: 80px;
  height: auto;
}
</style>
